package com.zkingsoft.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * @全局异常处理类
 */
@Service("com.zkingsoft.exception.GlobleExceptionResolver")
public class GlobleExceptionResolver implements HandlerExceptionResolver {

	public static Log log = LogFactory.getLog(GlobleExceptionResolver.class);
	
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
        String content = "";
		if (ex instanceof GlobleException) { //自己捕获的异常 throw new GlobleException("XXXX")
			GlobleException globleException = (GlobleException) ex;
			content = "系统错误信息：" + globleException.getMessage();
		} else {
			ex.printStackTrace();
			content = "系统出现错误请稍后再试！错误信息：" + ex.getMessage();
		}
		send(response, content);
		return null;
	}

	private static void send(HttpServletResponse response, String content) {
        
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            //若发送数据为null 则默认为""
            if(content == null){
                content = "";
            }
            out.write(content);
        }
        catch (IOException e) {
            log.error(e.getLocalizedMessage(), e);
        }
        finally {
            if (out != null)
                out.close();
        }
    }
	
}
